import os
from typing import List
from pydantic import BaseModel
import json


class Setting(BaseModel):
    # mysql+pool://user:passwd@ip:port/my_db?max_connections=8&stale_timeout=300
    db: str = "mysql+pool://user:passwd@ip:port/my_db?max_connections=8&stale_timeout=300"

    # api路由的公共前缀
    # 若前缀为"/api/v1" 则"/categories"路由则会变成"/api/v1/categories"
    api_prefix: str = "/api/v1"

    # 是否开启调试模式
    # 若开启则会对外开放swagger-ui的文档 同时打开代码变化时自动reload的功能
    api_debug: bool = False

    # CORS跨域设置 若为["*"]则允许所有地址跨域访问
    # 若列表内含有地址则仅允许列表内地址跨域访问
    api_cors_origins: List[str] = ["*"]


def getSetting(path: str):
    path = os.getenv("SETTINGPATH") if os.getenv("SETTINGPATH") else path
    try:
        with open(path, "r") as fp:
            ret = Setting(**json.loads(fp.read()))
            print(f"读取配置{path}成功。")
            return ret
    except Exception as e:
        print(f"读取配置{path}失败，使用setting.py中的默认配置。")
        return Setting()


setting = getSetting("./config/config.json")
